<template lang="html">
    <div class="wang-editor">
        <div ref="toolbar" class="toolbar"></div>
        <div ref="editor" class="text" :style="`height:${minHeight};max-height:${maxHeight}`"></div>
    </div>
</template>

<script>
// import defaultSettings from '@/settings'
import Editor from 'wangeditor'
import { admingetoss } from "@/api/index";
export default {
    name: 'WangEditor',
    model: {
        prop: 'value',
        event: 'change'
    },
    props: {
        minHeight: {
            type: String,
            default: '290px'
        },
        maxHeight: {
            type: String,
            default: ''
        },
        value: {
            type: String,
            default: ''
        },
        isClear: {
            type: Boolean,
            default: false
        }
    },
    data() {
        return {
            myValue: this.value,
            editor: null,
            info_: null,
            currentImg: '',
            uploadConfig: {
                headers: {
                    'Authorization': localStorage.getItem('token')
                },
            }
        }
    },
    watch: {
        isClear(val) {
            // 触发清除文本域内容
            if (val) {
                this.editor.txt.clear()
                this.info_ = null
            }
        },
        value(newVal) {
            if (newVal !== this.editor.txt.html()) {
                this.editor.txt.html(newVal)
            }
            this.myValue = newVal
        },
        myValue(newVal) {
            this.$emit('input', newVal)
        }
    },
    mounted() {
        this.seteditor()
        this.editor.txt.html(this.myValue)
    },
    methods: {
        generateTokens(key, file, insertImgFn) {
            return new Promise((resolve, reject) => {
                this.loading = true
                admingetoss({ type: 0 }).then((response) => {
                    const { data } = response
                    if (!data) {
                        this.$message.error('获取阿里云配置失败！请稍后再试！')
                    }
                    const tokens = new FormData()
                    file.startTime = new Date().getTime()
                    const dir = data.dir
                    tokens.append('key', dir + key)
                    tokens.append('policy', data.encodedPolicy)
                    tokens.append('OSSAccessKeyId', data.accessKeyId)
                    tokens.append('success_action_status', 200)
                    tokens.append('signature', data.postSignature)
                    tokens.append('file', file)
                    this.$axios.post(data.host, tokens, this.uploadConfig.headers).then(response => {
                        console.log(response)
                        this.loading = false
                    }).catch(error => {
                        console.log(error)
                        const fileAddress = dir + key
                        const url = data.host + fileAddress
                        insertImgFn(url)
                        this.loading = false
                    })
                    resolve(true)
                })
            }, () => {
                this.loading = false
                // eslint-disable-next-line no-undef
                reject(false)
            })
        },
        seteditor() {
            // http://192.168.2.125:8080/admin/storage/create
            this.editor = new Editor(this.$refs.toolbar, this.$refs.editor)
            this.editor.customConfig.uploadImgShowBase64 = false // base 64 存储图片
            this.editor.customConfig.uploadImgServer = true // 配置服务器端地址
            // this.editor.customConfig.uploadImgHeaders = {
            //     'Authorization': localStorage.getItem('token')
            // } // 自定义 header
            // this.editor.customConfig.uploadFileName = 'data' // 后端接受上传文件的参数名
            // this.editor.customConfig.uploadImgMaxSize = 2 * 1024 * 1024 // 将图片大小限制为 2M
            // this.editor.customConfig.uploadImgMaxLength = 1 // 限制一次最多上传 1 张图片
            // this.editor.customConfig.uploadImgTimeout = 3 * 60 * 1000 // 设置超时时间

            // 配置菜单
            this.editor.customConfig.menus = [
                'head', // 标题
                'bold', // 粗体
                'fontSize', // 字号
                'fontName', // 字体
                'italic', // 斜体
                'underline', // 下划线
                'strikeThrough', // 删除线
                'foreColor', // 文字颜色
                'backColor', // 背景颜色
                'link', // 插入链接
                'list', // 列表
                'justify', // 对齐方式
                'quote', // 引用
                'emoticon', // 表情
                'image', // 插入图片
                'table', // 表格
                'video', // 插入视频
                'code', // 插入代码
                'undo', // 撤销
                'redo', // 重复
                'fullscreen' // 全屏
            ]

            this.editor.customConfig.uploadImgHooks = {
                // 插入图片失败回调
                fail: (xhr, editor, result) => {
                },
                // 图片上传成功回调
                success: (xhr, editor, result) => {
                },
                // 网络超时的回调
                timeout: (xhr, editor) => {
                },
                // 图片上传错误的回调
                error: (xhr, editor) => {
                },
                // 图片上传成功，插入图片的回调
                customInsert: (insertImg, result, editor) => {
                    const url = result.data
                    insertImg(url)
                }
            }
            // 上传到阿里云的回调
            var that = this
            this.editor.customConfig.customUploadImg = function (resultFiles, insertImgFn) {
                const arr = resultFiles[0].name.split('.')
                let uid = resultFiles[0].uid
                const time = new Date().getTime()
                if (!uid) {
                    uid = time
                }
                const un_name = `${uid}.${arr[arr.length - 1]}`
                that.generateTokens(un_name, resultFiles[0], insertImgFn)
            }
            this.editor.customConfig.onchange = (html) => {
                this.info_ = html // 绑定当前逐渐地值
                this.$emit('on-change', this.info_) // 将内容同步到父组件中
            }
            // 创建富文本编辑器
            this.editor.create()
        }
    }
}
</script>

<style lang="scss">
.wang-editor {
    width: 100%;

    margin: 0 auto;
    position: relative;
    z-index: 0;
}

.toolbar {
    border: 1px solid #ccc;
}

.text {
    border: 1px solid #ccc;
    min-height: 500px;
}

// .wang-editor {
//   width: 100%;
//   margin: 0 auto;
//   position: relative;
//   z-index: 0;
//   .text {
//     .w-e-text {
//       padding: 0 15px;
//       // overflow-y: scroll;

//       overflow-y: initial;
//       // min-height: 335px;
//       font-size: 14px;
//     }
//   }
//   .w-e-toolbar {
//     display: -webkit-box;
//     display: -ms-flexbox;
//     display: flex;
//     padding: 0 5px;
//     /* flex-wrap: wrap; */
//     border-bottom: 1px solid #dcdfe6;
//   }
// }
</style>
